import React, { Component } from 'react';
import { Button, List, Image, Upload, message, Checkbox, Row, Col } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import Wheaders from '../../components/Headers';
import Http from '../../util/http';
import { WindManUtils } from '../../util/utils';
import './index.less';

class Usercenter extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userInfo: {},
            last_Reading: {},
            bookShelfList: [],
            isEdit: false,
            willDelete: [],
        }
    }

    render() {
        const { userInfo, bookShelfList, last_Reading, isEdit } = this.state;

        const onPreview = async file => {
            let src = file.url;
            if (!src) {
                src = await new Promise(resolve => {
                    const reader = new FileReader();
                    reader.readAsDataURL(file.originFileObj);
                    reader.onload = () => resolve(reader.result);
                });
            }
            const image = new Image();
            image.src = src;
            const imgWindow = window.open(src);
            imgWindow.document.write(image.outerHTML);
        };
        return (
            <div className='user-center'>
                {/* <Headers></Headers> */}
                <Wheaders left={'返回'} middle={'个人中心'} right={'首页'} />
                <div className={'headerWrap '}>
                    <div className={'user-header'}>
                        <Upload
                            action='http://lwa.hanlingsha.love:18191/File/uploadHeadIcon'
                            onPreview={onPreview}
                            onChange={({ file }) => {

                                if (file.status === 'done') {
                                    const headpic = file.response.resultData.n.url;
                                    Http.post('/User/changeUserInfo', {
                                        userName: userInfo.userName,
                                        headpic,
                                    }).then(response => {
                                        message.success('修改成功', 1, () => {
                                            const newuserInfo = { ...userInfo, headpic: headpic };
                                            this.setState({ userInfo: newuserInfo });
                                        });
                                    });
                                }
                            }}
                            showUploadList={false}
                        >
                            <img src={userInfo.headpic} alt='头像' />
                        </Upload>
                    </div>
                    <div className={'judgebRenewTure'}>
                        <p className={'user-name'}>{userInfo.userName}</p>
                        <p className={'balanceQ '}>{userInfo.coupon} 书券</p>
                        <Link className={'payRecord'} to={'/consumptionlog'}>消费记录</Link>
                    </div>
                </div>
                { last_Reading && <div className={'lately-read'}>
                    <div className={'latebox'}>
                        <span className={'posi_l'}>
                            <Image className={'ant-img'} src={last_Reading && last_Reading.coverUrl} preview={false} fallback={'http://image.hanlingsha.love/lwa/novel/lwa-default-novel-cover.jpeg'} />
                        </span>
                        <div className={'layetest'}>
                            <Link to={{
                                pathname: '/reading', state: {
                                    novelInfo: last_Reading,
                                    orderNum: last_Reading.orderNum,
                                }
                            }}>
                                <p className={'simple'}>{last_Reading.novelName}</p>
                                <p className={'simple fontcolor-ef3a3a'}>{last_Reading.chapterName}</p>
                                <span className={'simple fontcolor-999'}>最近阅读</span>
                            </Link>
                            <Link className={'posi_r'} to={'/history'}>
                                最近阅读
                            </Link>
                        </div>
                    </div>
                </div>}
                <div className={'bcview-btn'}>
                    <div className={'btn-group'}>
                        <Row>
                            <Col span={12} style={{textAlign: 'left'}}>
                                <span style={{fontSize: '22px'}}>我的书架</span>
                            </Col>
                            <Col span={12} style={{textAlign: 'right', paddingTop: '10px'}}>
                                {isEdit ?
                                    <div>
                                        <Button className={'btn'} type='default' onClick={this.goEdit.bind(this)}>删除</Button>
                                        <Button className={'btn'} type='default' danger onClick={() => {
                                            this.setState({ isEdit: !this.state.isEdit });
                                        }}>取消</Button>
                                    </div> :
                                    <Button className={'btn'} danger type='default' onClick={() => {
                                        this.setState({ isEdit: !this.state.isEdit });
                                    }}>编辑</Button>}
                            </Col>
                        </Row>
                    </div>
                </div>
                <div className={'content'}>
                    <List
                        grid={{
                            gutter: 16,
                            xs: 3,
                            sm: 3,
                            md: 3,
                            lg: 4,
                            xl: 6,
                            xxl: 6,
                        }}
                        dataSource={bookShelfList}
                        renderItem={item => (
                            <List.Item className={'list-item'}>
                                { (item && item.addBook) ?
                                    <div className={'addBook'} onClick={() => {
                                        this.props.history.push('/');
                                    }} >
                                        <PlusOutlined />
                                    </div>
                                    :
                                    <div>
                                        <div className='coverPic' onClick={() => {
                                            this.props.history.push({ pathname: '/details', state: { novelId: item.novelId } });
                                        }}>
                                            <Image className={'ant-img'} src={item.coverUrl} preview={false} fallback={'http://image.hanlingsha.love/lwa/novel/lwa-default-novel-cover.jpeg'} />
                                        </div>
                                        <span className={'title'}>{item.novelName}</span>
                                    </div>
                                }
                                {
                                    isEdit && !(item && item.addBook) ?
                                        <Checkbox className={'delete-check'} data-delete={item.novelId} onChange={e => {
                                            const willDelete = this.state.willDelete;
                                            if (e.target.checked) {
                                                this.setState({ willDelete: [...this.state.willDelete, e.target['data-delete']] })
                                            }
                                            else {
                                                willDelete.splice(willDelete.indexOf(e.target['data-delete']), 1);
                                            }
                                        }} /> :
                                        ''
                                }

                            </List.Item>
                        )}
                    />
                </div>

                {/* 退出登录 */}
                <div className={'loginOut'}>
                    <Button className={'btn'} type={'default'} shape='round' block onClick={this.loginOut.bind(this)}>
                        退出登录
                    </Button>
                </div>
            </div>
        );
    }

    UNSAFE_componentWillMount() {
    }

    componentDidMount() {
        if (!WindManUtils.getStorage('user_info')) {
            return message.error('未登录', 1, () => { this.props.history.push('/login'); });
        }
        const { userId } = WindManUtils.getStorage('user_info');
        if(!userId) {
            this.props.history.push('/login');
        }
        this.getUserCenter(userId);
        this.getReadLog();
        this.getBookShelfList();
    }

    getBookShelfList = async () => {
        await Http.get('/Shelf/lists').then(response => {
            this.setState({ bookShelfList: [...response.resultData, { addBook: true }] });
        })
    }

    getReadLog = async () => {
        await Http.get('/Novel/getReadLog').then(response => {
            const last_Reading = response.resultData[0];
            this.setState({ last_Reading });
        })
    }

    getUserCenter = async (id) => {
        await Http.get('/User/userCenter', {
            personId: id,
        }).then(response => {
            this.setState({ userInfo: response.resultData });
        })
    }

    goEdit() {
        const deleteNovel = (id) => {
            Http.get('/Shelf/delete', {
                novelId: id,
            }).then(response => {
                return true;
            });
        };
        this.state.willDelete.map(id => {
            deleteNovel(id);
        });
        message.success('删除成功', 1, () => {
            this.setState({ isEdit: false, willDelete: [], bookShelfList: [] }, () => {
                this.getBookShelfList()
            });
        })
    }

    loginOut() {
        Http.post('/User/logOut').then(response => {
            WindManUtils.removeStorage('user_info');
            message.success('退出成功', 1, () => {
                this.props.history.push('/');
            })
        });
    }
}
export default Usercenter;


